const express = require('express')
const router = express.Router()
const Admin = require('../../models/Admin')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const passport = require('passport')
const  keys =  require('../../config/keys')
router.post('/login', (req, res) => {
    const username = req.body.username
    const password = req.body.password
    Admin.findOne({ username: username })
        .then(admin => {
            if (!admin) {
                return res.json({msg:'未查到此人或非管理员',status:201})
            }
            bcrypt.compare(password, admin.password)
                .then(isMath => {
                    if (isMath) {
                        const rule = { id: admin.id, name: admin.username,}
                        jwt.sign(rule, keys.secretOrKey, { expiresIn: 3600 }, (err, token) => {
                            if (err) return err
                            res.json({
                                status:200,
                                success: true,
                                token: 'Bearer ' + token,
                                menu: admin.menu
                            })
                        })
                    } else {
                        return res.json({status:202,msg:'密码错误'})
                    }
                })
        })
})
router.post('/register', (req, res) => {
    if (req.body.powermessage === 'wqz666') {
        Admin.findOne({ username: req.body.username })
            .then(admin => {
                if (admin) {
                    return res.json({msg:'此用户名已被注册',status:201})
                }
                const newAdmin = new Admin({
                    password: req.body.password,
                    username: req.body.username,
                })
                bcrypt.genSalt(10, function (err, salt) {
                    bcrypt.hash(newAdmin.password, salt, (err, hash) => {
                        if (err) throw err;
                        newAdmin.password = hash;
                        newAdmin.save()
                            .then(admin => res.json({user:admin,status:200}))
                            .catch(err => console.log(err))
                        // Store hash in your password DB.
                    })
                })
            })
    }else{
        return res.json({status:203,msg:'授权码错误'})
    }

})
module.exports = router
